Excel sheet column title¶
Time: O(LogN)=O(1); Space: O(1); easy
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
Example 1:
Input: n = 1
Output: “A”
Example 2:
Input: n = 28
Output: “AB”
Example 3:
Input: n = 701
Output: “ZY”
[1]:
class Solution1(object):
def convertToTitle(self, n) -> str:
"""
:type n: int
:rtype: str
"""
result, dvd = "", n
while dvd:
result += chr((dvd - 1) % 26 + ord('A'))
dvd = (dvd - 1) // 26
return result[::-1]
[2]:
s = Solution1()
n = 1
assert s.convertToTitle(n) == "A"
n = 28
assert s.convertToTitle(n) == "AB"
n = 701
assert s.convertToTitle(n) == "ZY"
# for i in range(1, 29):
# print(Solution().convertToTitle(i))